const mongoose = require('../db/index').mongoose;
const { userModel, productModel, hospitalModel, doctorModel, bannerModel } = require('../db/models/cosmetic');
const fs = require('fs');
const path = require('path');

// 读取JSON文件
function readJsonFile(filePath) {
  try {
    const data = fs.readFileSync(filePath, 'utf8');
    return JSON.parse(data);
  } catch (error) {
    console.error(`读取文件失败: ${filePath}`, error);
    return null;
  }
}

// 导入轮播图数据
async function importBanners() {
  console.log('开始导入轮播图数据...');
  const bannersData = readJsonFile(path.join(__dirname, '../data/banners.json'));
  
  if (!bannersData) {
    console.log('轮播图数据文件读取失败');
    return;
  }

  try {
    // 清空现有数据
    await bannerModel.deleteMany({});
    
    // 导入数据 - 轮播图是数组格式
    const banners = bannersData.map(banner => ({
      ...banner,
      createTime: new Date(banner.createTime || Date.now())
    }));
    
    await bannerModel.insertMany(banners);
    console.log(`轮播图数据导入成功，共 ${banners.length} 条`);
  } catch (error) {
    console.error('轮播图数据导入失败:', error);
  }
}

// 导入商品数据
async function importProducts() {
  console.log('开始导入商品数据...');
  const productsData = readJsonFile(path.join(__dirname, '../data/products.json'));
  
  if (!productsData) {
    console.log('商品数据文件读取失败');
    return;
  }

  try {
    // 清空现有数据
    await productModel.deleteMany({});
    
    // 导入数据
    const products = [];
    for (const category in productsData) {
      productsData[category].forEach(product => {
        products.push({
          ...product,
          createTime: new Date(product.createTime || Date.now())
        });
      });
    }
    
    await productModel.insertMany(products);
    console.log(`商品数据导入成功，共 ${products.length} 条`);
  } catch (error) {
    console.error('商品数据导入失败:', error);
  }
}

// 导入医院数据
async function importHospitals() {
  console.log('开始导入医院数据...');
  const hospitalsData = readJsonFile(path.join(__dirname, '../data/hospitals.json'));
  
  if (!hospitalsData) {
    console.log('医院数据文件读取失败');
    return;
  }

  try {
    // 清空现有数据
    await hospitalModel.deleteMany({});
    
    // 导入数据
    const hospitals = [];
    for (const category in hospitalsData) {
      hospitalsData[category].forEach(hospital => {
        hospitals.push({
          ...hospital,
          createTime: new Date(hospital.createTime || Date.now())
        });
      });
    }
    
    await hospitalModel.insertMany(hospitals);
    console.log(`医院数据导入成功，共 ${hospitals.length} 条`);
  } catch (error) {
    console.error('医院数据导入失败:', error);
  }
}

// 导入医生数据
async function importDoctors() {
  console.log('开始导入医生数据...');
  const doctorsData = readJsonFile(path.join(__dirname, '../data/doctors.json'));
  
  if (!doctorsData) {
    console.log('医生数据文件读取失败');
    return;
  }

  try {
    // 清空现有数据
    await doctorModel.deleteMany({});
    
    // 导入数据
    const doctors = [];
    for (const category in doctorsData) {
      doctorsData[category].forEach(doctor => {
        doctors.push({
          ...doctor,
          createTime: new Date(doctor.createTime || Date.now())
        });
      });
    }
    
    await doctorModel.insertMany(doctors);
    console.log(`医生数据导入成功，共 ${doctors.length} 条`);
  } catch (error) {
    console.error('医生数据导入失败:', error);
  }
}

// 主函数
async function importAllData() {
  try {
    console.log('开始导入数据到MongoDB...');
    
    // 等待数据库连接
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 导入所有数据
    await importBanners();
    await importProducts();
    await importHospitals();
    await importDoctors();
    
    console.log('所有数据导入完成！');
    
    // 验证数据
    const bannerCount = await bannerModel.countDocuments();
    const productCount = await productModel.countDocuments();
    const hospitalCount = await hospitalModel.countDocuments();
    const doctorCount = await doctorModel.countDocuments();
    
    console.log('\n数据统计:');
    console.log(`轮播图: ${bannerCount} 条`);
    console.log(`商品: ${productCount} 条`);
    console.log(`医院: ${hospitalCount} 条`);
    console.log(`医生: ${doctorCount} 条`);
    
    // 测试分类查询
    console.log('\n测试分类查询:');
    const productCategories = await productModel.distinct('category');
    const hospitalCategories = await hospitalModel.distinct('category');
    const doctorCategories = await doctorModel.distinct('category');
    
    console.log(`商品分类: ${productCategories.join(', ')}`);
    console.log(`医院分类: ${hospitalCategories.join(', ')}`);
    console.log(`医生分类: ${doctorCategories.join(', ')}`);
    
  } catch (error) {
    console.error('数据导入过程中发生错误:', error);
  } finally {
    // 关闭数据库连接
    mongoose.connection.close();
    console.log('数据库连接已关闭');
  }
}

// 运行导入脚本
importAllData();
